<template>
    <el-dialog :close-on-click-modal="false" :visible.sync="show" width="800px" @close="close" append-to-body>
        <div slot="title" class="title"> 
            <span>选择群</span>
        </div>
        <div v-loading="loading" class="body">
            <div class="checkbox-list">
                <div class="filter">
                    <el-input
                        class="filter-input"
                        ref="filter-input"
                        size="mini"
                        :placeholder="'请输入群名称' "
                        v-model="friendsFilterKeyword"
                        autofocus="true"
                        clearable>
                    </el-input>

                    <el-radio-group class="radio-group" v-model="filterType" size="mini" v-if="type===0">
                        <el-radio-button :label="1">群主</el-radio-button>
                        <el-radio-button :label="2">非群主</el-radio-button>
                    </el-radio-group>  

                    
                </div>
                <div class="filter">
                    <div class="number-group">
                        <el-input
                        class="filter-min"
                        size="mini"
                        v-model="min"
                        placeholder="请输入最少" >
                        </el-input>
                        <span>&nbsp;-&nbsp;</span>
                        <el-input
                            class="filter-max"
                            size="mini"
                            v-model="max"
                            placeholder="请输入最多" >
                        </el-input>
                    </div>
                    <el-button-group class="filter-selected">
                        <el-button @click="selectAll" type="primary" size="mini">全选</el-button>
                        <el-button @click="selectInvert" type="primary" size="mini">反选</el-button>
                    </el-button-group>  
                </div>
                <div class="scroller">
                    <el-row class="friend-list">
                        <div class="friend-list-inner">
                            <div class="friend-item-grid" v-for="(friend) in filteredFriends" :key="friend.id">
                                <label v-if="initialDisabled&&initialNos.includes(friend.groupno)" class="friend-item is-success is-success-disabled">
                                    <group 
                                        :avatar="friend.avatar"
                                        :name="friend.groupname"
                                        :member="friend.personnum" 
                                        :friend="friend.friendNum"
                                    />
                                    <div class="friend-item-status-label">
                                        <i class="friend-item-check-success el-icon-check"></i>
                                    </div>
                                </label>

                                <label v-else @click="checkfriend(friend)" :class="['friend-item',checkedIds.includes(friend.id)&&'is-success']">
                                    <group 
                                        :avatar="friend.avatar"
                                        :name="friend.groupname"
                                        :member="friend.personnum" 
                                        :friend="friend.friendNum"
                                    />
                                    <div class="friend-item-status-label">
                                        <i class="friend-item-check-success el-icon-check"></i>
                                    </div>
                                </label>
                                
                            </div>    
                        </div>
                    </el-row>
                </div>
            </div>
            <el-divider class="divider" direction="vertical"></el-divider>
            <div class="checkbox-result">
                <div class="result-title">
                    已选择群（{{checkedfriends.length}}）
                </div>
                <div class="checked-list" ref="checked-list">
                    <div class="friend-list-inner" >
                        <div class="friend-col-item" v-for="(friend) in checkedfriends" :key="friend.id">
                            <el-avatar shape="square" :size="30" :src="friend.avatar"></el-avatar>
                            <div class="col-item-nick">{{friend.groupname||'群聊天'}}</div>
                            <!-- <div>{{friend.friendalias||friend.friendwxid}}</div> -->
                            <el-button v-if=" !(initialDisabled&&initialNos.includes(friend.groupno))" @click="checkfriend(friend)" icon="el-icon-close" size="mini" circle></el-button>
                        </div>
                    </div>
                </div>
                
                <div class="button-group">
                    <el-button type="primary" @click="confirm" :disabled="!checkedIds.length">确定</el-button>
                    <el-button plain @click="cancel">取消</el-button>
                </div>
                
            </div>
            
        </div>
    </el-dialog> 
    
</template>
<script>
import group from '@/components/group'
import pinyin from '@/lib/pinyin'
/**
 * getSelectFriends
 * params = {}
 *  csid,wxaccout,
 *  multiple 多选单选
 *  type 只展示类别 0 全部 1 群主 2 非群主
 *  filterType 默认展示类别 1 群主 2 非群主
 * filterNos 过滤掉的选项
 * initialNos 初始选择
 * initialDisabled 初始化选择是否禁用删除  true 禁用 false 可用
 * byMemberWxId: 通过成员wxid过滤
 */
export default {
    name:'dialog-select-group',
    props:['visible'],
    components:{ group },
    data(){
        return {
            show:false,
            loading:true,
            
            friendsFilterKeyword:'',
            checkedIds:[],
            friendsMap:{},
            friends:[],

            // UI 控制变量
            multiple:false, // 是否多选
            type:0,         // 展示类别
            filterType:1 ,  // 默认展示类别（type==0时生效）
            filterNos:[],  // 过滤掉
            initialNos:[],
            initialDisabled:false,
            byMemberWxId:'',
            min:'',
            max:''

        }    
    },
    
    computed:{
        filteredFriends() {
            const filterType = this.filterType
            const keyword = this.friendsFilterKeyword
            const keywordchars = pinyin.getFullChars(keyword).toLocaleLowerCase()
            return this.friends.filter(friend=>{
                const chars = pinyin.getFullChars(friend.groupname).toLocaleLowerCase()
                if(this.filterNos.includes(friend.groupno))return false

                if(this.min!==''){
                    if(friend.personnum<this.min)return false   
                }
                if(this.max!==''){
                    if(friend.personnum>this.max)return false    
                }

                if( filterType===1 ){
                    return chars.indexOf(keywordchars)>-1 && friend.isfirst===1  
                }else{
                    return chars.indexOf(keywordchars)>-1 && friend.isfirst!==1 
                }

            })
        },
        checkedfriends(){
            return this.checkedIds.map(id=>this.friendsMap[id])
        }
         
    },
    watch:{
        min(){},
        max(){}
    },
    methods:{
        checkfriend(friend){
            if(this.checkedIds.includes(friend.id)){ // 存在
                if(this.multiple){
                    const index = this.checkedIds.indexOf(friend.id)
                    this.checkedIds.splice(index,1)
                }else{
                    this.checkedIds = []     
                }
            }else{ // 不存在
                if(this.multiple){
                    this.checkedIds.push(friend.id)
                }else{
                    this.checkedIds = [friend.id] 
                }
                
            }
            this.scrollToEnd()
        },
        selectAll(){
            this.filteredFriends.forEach(item=>{
                if(!this.checkedIds.includes(item.id)){
                    this.checkedIds.push(item.id)
                }    
            })  
        },
        selectInvert(){
            const checkedIds = this.checkedIds;
            this.filteredFriends.forEach(item=>{
                if(!checkedIds.includes(item.id)){
                    checkedIds.push(item.id)
                }else{
                    const index = checkedIds.indexOf(item.id)  
                    if(this.initialDisabled && this.initialNos.includes(item.groupno)){

                    }else{
                        checkedIds.splice(index,1) 
                    }
                     
                }    
            })
            this.checkedIds = checkedIds
        },
        scrollToEnd(){
            const el_list = this.$refs['checked-list']
            const el_inner = el_list.firstChild
            this.$nextTick(()=>el_list.scrollTo(0,el_inner.offsetHeight))
        },
        requestFriends(params){
            this.loading = true
            this.$api.group.list(params)
                .then(result=>{
                    this.loading = false
                    const data = this.formatData(result)
                    this.friends = data
                })
                .catch(e=>{
                    this.loading = false
                })
        },
        requestByMemberWxid(params){
            this.loading = true
            this.$api.group.groupsForMemeber(params)
                .then(result=>{
                    this.loading = false
                    const data = this.formatData(result)
                    this.friends = data
                })
                .catch(e=>{
                    this.loading = false
                })
        },
        formatData(data){
            let map = {}
            let initialNos = []
            // const  
            data = data.map(item=>{
                map[item.id] = item
                if(this.initialNos.includes(item.groupno)){
                    initialNos.push(item.id)
                }
                return item
            })

            this.friendsMap = map
            this.checkedIds = initialNos
            return data;
        },
        getSelectFriendsAsync( params = {} ){
            return new Promise((resolve,reject)=>{
                this.getSelectFriends({...params,callback:(result) => {
                    resolve(result)    
                }})    
            })        
        },
        getSelectFriends( params ){
            this.callback = params.callback
            this.multiple = params.multiple
            this.filterNos = params.filterNos || []
            this.initialNos = params.initialNos || []
            this.initialDisabled = params.initialDisabled || false
            this.type = params.type || 0,         // 展示类别
            this.filterType = params.filterType || 1 
            this.byMemberWxId = params.byMemberWxId || ''

            if( params.type )this.filterType=this.type

            if(params.byMemberWxId){
                this.requestByMemberWxid({
                     csId: params.csid,wxAccount: params.wxaccount,memberWxId:params.byMemberWxId     
                })
            }else{
                this.requestFriends(
                 { csid: params.csid,wxaccount: params.wxaccount } 
                )
            }
            
            this.show = true 
        },
        reset(){
            this.result = undefined  
            this.checkedIds = []  
            this.friendsFilterKeyword=''
            this.friendsMap = {}
            this.friends = []
            this.filterNos = []
        },
        confirm(){
            this.result = this.checkedfriends
            this.show = false
        },
        cancel(){
            this.show = false
        },
        close(){
            this.callback(this.result)
            this.reset()
        }
    }    
}
</script>

<style scoped>
.title{
    display: flex; flex-direction: row;justify-content: space-between;
}
.body{
    display: flex; flex-direction: row; height: 500px;
}

.filter{
    padding:0 10px 10px;
    display: flex;
    flex-direction: row;
    align-items: center;
}
.radio-group{
    flex-shrink: 0;
    margin-left: 10px;
}
.filter-input{
}
.number-group{
    display: flex;
    flex-direction: row;
    flex:1;
    align-items: center;
}
.filter-selected{
    flex-shrink: 0;
    margin-left: 10px;
}
.filter-min,
.filter-max{
}
.divider{
    display: block;
    height: 100%;
}
.checkbox-list{
    display: flex; flex-direction: column;
    width: 400px;
    flex-shrink: 0;  
}
.friend-list-inner{
    overflow: hidden;
}
.scroller{
    height: 100%;
    overflow: auto;
}

.friend-item-grid{
    width: 50%;
    float: left;
    padding: 5px;
    box-sizing: border-box;
}
.friend-item{
    display: block;
    position: relative;
    overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 3px;
    box-sizing: border-box;
    padding: 10px 10px 10px 10px;
}

.friend-item-status-label {
    position: absolute;
    right: -17px;
    top: -7px;
    width: 46px;
    height: 26px;
    background: #13ce66;
    text-align: center;
    transform: rotate(45deg);
    box-shadow: 0 1px 1px #ccc;
    display: none
}
.friend-item-check-success{
    color: #fff;
    font-size: 12px;
    margin-top: 12px;
    transform: rotate(-45deg);
}
.is-success .friend-item-status-label{
    display: block
}
.is-success-disabled .friend-item-status-label{
    background: #ddd;
}


.checkbox-result{
    display: flex;
    flex-direction: column;
    flex:1;
}
.result-title{
    padding: 10px;
}
.checked-list{
    height: 100%;
    overflow:auto;
}

.friend-col-item{
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 5px 10px;
    border-radius: 5px;
}
.friend-col-item:hover{
    background: #f6f6f6
}
.col-item-nick{
    flex:1;
    padding-left: 10px;
}
.button-group{
    padding: 10px;
}
</style>